<?php

namespace App\Console\Commands\System;

use App\Library\Common\DateTool;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;

class ClearOldOssFile extends Command
{
    protected $signature = 'system:clear_old_oss_files';

    protected $description = '自动清空几天前OSS临时文件';

    protected array $prefixes = [
        'tmp/',
        'export/rms/'
    ];

    // 自动删除三天前的
    const DAYS_BEFORE = 3;

    public function handle()
    {
        // 获得所有包含的前缀
        $prefixes = [];
        foreach ($this->prefixes as $prefix) {
            $prefixes = array_merge(FileUtil::listObjects(['prefix' => $prefix])->getPrefixList(), $prefixes);
        }

        // 设置正则规则
        $pattern = '/\b\d{8}\b/';

        foreach ($prefixes as $item) {

            // 正则匹配并且获得date
            preg_match($pattern, $item->getPrefix(), $matches);
            if (empty($matches)) {
                continue;
            }
            $date = $matches[0];

            if (mb_strlen($date) != 8) {
                continue;
            }
            if (!is_numeric($date)) {
                continue;
            }
            $date = mb_substr($date, 0, 4) . '-' . mb_substr($date, 4, 2) . '-' . mb_substr($date, 6, 2);
            if (!DateTool::isDate($date)) {
                continue;
            }
            if (strtotime($date) > Carbon::now()->subDays(static::DAYS_BEFORE)->startOfDay()->timestamp) {
                continue;
            }
            // 删除里面的文件和文件夹
            $this->deleteAll($item->getPrefix());
        }
        return 0;
    }

    protected function deleteAll(string $prefix)
    {
        // 判断是否以这个数组任何一个元素为开头的
        $delRes = false;
        foreach ($this->prefixes as $prefixItem) {
            if (Str::startsWith($prefix, $prefixItem)) {
                $delRes = true;
                break;
            }
        }

        if (!$delRes) {
            $prefixStr = implode('或', $this->prefixes);
            throw new \RuntimeException("只能删除 {$prefixStr} 前缀的文件");
        }

        // 删除逻辑
        $listInfo = FileUtil::listObjects(['prefix' => $prefix]);

        foreach ($listInfo->getObjectList() as $objectInfo) {
            FileUtil::deleteObject($objectInfo->getKey());
        }
        foreach ($listInfo->getPrefixList() as $prefixInfo) {
            $this->deleteAll($prefixInfo->getPrefix());
        }
    }
}
